package com.example.vendingmachine.controller;

import com.example.vendingmachine.dto.UserDTO;
import com.example.vendingmachine.dto.UserQuery;
import com.example.vendingmachine.entity.User;
import com.example.vendingmachine.service.UserService;
import com.example.vendingmachine.common.Result;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 分页查询用户列表
     *
     * @param query 查询条件
     * @return 分页用户列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('user:list')")
    public Result<PageInfo<User>> list(UserQuery query) {
        return Result.success(userService.listUsers(query));
    }

    /**
     * 获取用户详情
     *
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('user:list')")
    public Result<User> getInfo(@PathVariable Long id) {
        return Result.success(userService.getUserById(id));
    }

    /**
     * 新增用户
     *
     * @param userDTO 用户信息
     * @return 新增的用户ID
     */
    @PostMapping
    @PreAuthorize("hasAuthority('user:add')")
    public Result<Long> add(@Validated @RequestBody UserDTO userDTO) {
        return Result.success(userService.createUser(userDTO));
    }

    /**
     * 更新用户
     *
     * @param id 用户ID
     * @param userDTO 用户信息
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('user:edit')")
    public Result<Void> update(@PathVariable Long id, @Validated @RequestBody UserDTO userDTO) {
        userDTO.setId(id);
        userService.updateUser(userDTO);
        return Result.success();
    }

    /**
     * 删除用户
     *
     * @param id 用户ID
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('user:delete')")
    public Result<Void> delete(@PathVariable Long id) {
        userService.deleteUser(id);
        return Result.success();
    }

    /**
     * 更新用户状态
     *
     * @param id 用户ID
     * @param status 状态
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasAuthority('user:edit')")
    public Result<Void> updateStatus(@PathVariable Long id, @RequestParam String status) {
        userService.updateUserStatus(id, status);
        return Result.success();
    }
} 